using System;
using System.IO;

namespace Beetle;

public class ArraySegmentStream : Stream
{
	private byte[] a;

	private int b;

	private int c;

	private int d;

	public override bool CanRead => true;

	public override bool CanSeek => true;

	public override bool CanWrite => true;

	public override long Length => d;

	public override long Position
	{
		get
		{
			return c;
		}
		set
		{
			c = (int)value;
		}
	}

	public ArraySegmentStream(byte[] data)
	{
		a = data;
		d = 0;
		c = 0;
		b = 0;
	}

	public override void Flush()
	{
	}

	public override int Read(byte[] buffer, int offset, int count)
	{
		int num = d - c;
		if (num > count)
		{
			num = count;
		}
		if (num <= 0)
		{
			return 0;
		}
		if (num <= 8)
		{
			int num2 = num;
			while (--num2 >= 0)
			{
				buffer[offset + num2] = a[c + num2];
			}
		}
		else
		{
			Buffer.BlockCopy(a, c, buffer, offset, num);
		}
		c += num;
		return num;
	}

	public override long Seek(long offset, SeekOrigin origin)
	{
		switch (origin)
		{
		case SeekOrigin.Begin:
		{
			int num2 = (c = b + (int)offset);
			break;
		}
		case SeekOrigin.Current:
			c += (int)offset;
			break;
		case SeekOrigin.End:
		{
			int num = (c = d + (int)offset);
			break;
		}
		}
		return c;
	}

	public override void SetLength(long value)
	{
		int num = (d = b + (int)value);
		if (c > num)
		{
			c = num;
		}
	}

	public override void Write(byte[] buffer, int offset, int count)
	{
		int num = c + count;
		if (num > d)
		{
			d = num;
		}
		if (count <= 8 && buffer != a)
		{
			int num2 = count;
			while (--num2 >= 0)
			{
				a[c + num2] = buffer[offset + num2];
			}
		}
		else
		{
			Buffer.BlockCopy(buffer, offset, a, c, count);
		}
		c = num;
	}
}
